package org.ricks.db;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2020/12/2316:48
 */
public class DatePropertyHandler implements PropertyHandler {
    public DatePropertyHandler() {
    }

    public boolean match(Class<?> parameter, Object value) {
        if (value instanceof Date) {
            String targetType = parameter.getName();
            if ("java.sql.Date".equals(targetType)) {
                return true;
            }

            if ("java.sql.Time".equals(targetType)) {
                return true;
            }

            if ("java.sql.Timestamp".equals(targetType)) {
                return true;
            }
        }

        return false;
    }

    public Object apply(Class<?> parameter, Object value) {
        String targetType = parameter.getName();
        if ("java.sql.Date".equals(targetType)) {
            value = new java.sql.Date(((Date)value).getTime());
        } else if ("java.sql.Time".equals(targetType)) {
            value = new Time(((Date)value).getTime());
        } else if ("java.sql.Timestamp".equals(targetType)) {
            Timestamp tsValue = (Timestamp)value;
            int nanos = tsValue.getNanos();
            value = new Timestamp(tsValue.getTime());
            ((Timestamp)value).setNanos(nanos);
        }

        return value;
    }
}